package com.msy.mai.launch.web.strategy.factory;

import com.msy.mai.common.core.constants.MessageConst;
import com.msy.mai.launch.web.strategy.TokenGranterStrategy;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.security.InvalidParameterException;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 授权认证策略处理类（策略工厂）
 */
@Slf4j
@Component
public class TokenGranterFactory implements BeanPostProcessor {

    /**
     * 策略缓存池
     */
    private static final ConcurrentHashMap<String, TokenGranterStrategy> concurrentHashMap = new ConcurrentHashMap<>();

    @Nullable
    public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
        // 初始化限流策略实现类
        if (bean instanceof TokenGranterStrategy) {
            TokenGranterStrategy strategy = (TokenGranterStrategy) bean;
            concurrentHashMap.put(strategy.getKey(), strategy);
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    public TokenGranterStrategy getStrategy(String strategyKey) {
        TokenGranterStrategy strategy = concurrentHashMap.get(strategyKey);
        if (Objects.isNull(strategy)) {
            log.error("{}，策略类型type：{}", MessageConst.AUTH_POLICY_TYPE_NOT_EXIST, strategyKey);
            throw new InvalidParameterException(MessageConst.AUTH_POLICY_TYPE_NOT_EXIST);
        }
        return strategy;
    }

}
